//
//  KZBarWaveView.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/8/30.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZBarWaveView.h"

@implementation KZBarWaveView
{
    NSTimer *_timer;
}

- (instancetype)init {
    
    if (self = [super init]) {
        
    }
    return self;
}

- (void)layoutSubviews {
    
    [super layoutSubviews];
    [self setupUI];
    
}
- (void)setupUI {
    
    
    CGFloat margin = 6;
    
    for (int i = 0; i < 5; i ++) {
        
        CAShapeLayer *barLayer = [CAShapeLayer layer];
        barLayer.lineWidth = 4;
        barLayer.strokeColor = KZThemeColor2.CGColor;
        [self.layer addSublayer:barLayer];
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        CGFloat x = barLayer.lineWidth / 2 + (barLayer.lineWidth + margin) * i;
        CGFloat y = 0;
        [path moveToPoint:CGPointMake(x, y)];
        y = y + self.height;
        [path addLineToPoint:CGPointMake(x, y)];
        
        barLayer.path = path.CGPath;
    }
    
    for (int i = 0; i < 5; i ++) {
        
        CAShapeLayer *barLayer = [CAShapeLayer layer];
        barLayer.lineWidth = 4;
        barLayer.strokeColor = KZThemeColor2.CGColor;
        [self.layer addSublayer:barLayer];
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        CGFloat x = self.width - barLayer.lineWidth / 2 - (barLayer.lineWidth + margin) * i;
        CGFloat y = 0;
        [path moveToPoint:CGPointMake(x, y)];
        y = y + self.height;
        [path addLineToPoint:CGPointMake(x, y)];
        
        barLayer.path = path.CGPath;
    }
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:true];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction {
    
    for (int i = 0; i < self.layer.sublayers.count; i ++) {

        CAShapeLayer *layer = (CAShapeLayer *)self.layer.sublayers[i];
        CGFloat random = arc4random_uniform(50) / 100.0;
        layer.strokeStart = 0.5-random;
        layer.strokeEnd = 0.5+random;
    }
}

- (void)startSoucre {
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:true];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)freeSource {
    [_timer invalidate];
    _timer = nil;
}
- (void)pauseSource {
    [_timer setFireDate:[NSDate distantFuture]];
}
- (void)beginSource {
    [_timer setFireDate:[NSDate date]];
}

@end
